/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/no-array-index-key */
/* eslint-disable react/jsx-no-bind */
import React, { forwardRef, useState, useEffect } from 'react';
import { Input, Row, Col, Button, Icon, Popover, Tag, Popconfirm, message } from 'antd';
import { isEmpty } from 'lodash';
import styles from './styles.less';

const infoContent = (
  <div style={{ width: 300 }}>
    <div>维护多个关键字用“、”隔开，</div>
    <div>例如：北京、上海</div>
    <div>维护组合关键字用“+”连接</div>
    <div>例如：北京+海淀</div>
    <div>
      当关键字为
      <span className={styles.red}>北京+海淀、上海</span>
      时，表示收件地址内包含关键字
      <span className={styles.red}>北京</span>和<span className={styles.red}>海淀</span>
      时对应该格口，或者包含
      <span className={styles.red}>上海</span>
      时对应格口
    </div>
  </div>
);

const initRules = [
  {
    type: 'keyword',
    rule: '',
    value: '',
    placeholder: '请输入地址关键字',
    width: 180,
  },
];

const KeyWordsInput = forwardRef((props, ref) => {
  const { value = [], onChange } = props;
  const [rules, setRules] = useState([...initRules]);

  const onAdd = () => {
    if (rules.some(val => !val.value || isEmpty(val.value))) {
      message.error('请填写完整的地址关键字');
      return;
    }
    // const sortKey = ['keyword', 'and', 'range', 'odd', 'even'];
    // const sortRules = [...rules].sort((a, b) => {
    //   const aIndex = sortKey.indexOf(a.type);
    //   const bIndex = sortKey.indexOf(b.type);
    //   return aIndex - bIndex;
    // });

    let keywords = '';

    rules.forEach((item, index) => {
      if (item.type == 'range') {
        const rangeValue = `${item.value[0]}-${item.value[1]}`;
        if (keywords.includes('(')) {
          keywords = keywords.replace('(', `(${rangeValue}`);
        } else {
          keywords += `${index == 0 || !item.showAnd ? '' : '+'}(${rangeValue})`;
        }
      } else if (item.type == 'odd' || item.type == 'even') {
        if (keywords.includes(')')) {
          keywords = keywords.replace(')', `${item.value})`);
        } else {
          keywords += `${index == 0 || !item.showAnd ? '' : '+'}(${item.value})`;
        }
      } else {
        keywords += `${index == 0 || !item.showAnd ? '' : '+'}${item.value}`;
      }
    });

    if (value.includes(keywords)) {
      message.warning('请勿添加重复的关键词');
      return;
    }

    const arr = [...value, keywords];
    onChange && onChange(arr);
  };

  const onDelete = (e, index) => {
    e.preventDefault();
    value.splice(index, 1);
    onChange && onChange(value);
  };

  const onInputChange = (e, rule, index, range) => {
    e.persist();
    const { value: inputVal } = e.target;
    setRules(prevRules => {
      if (rule == 'range' && range) {
        prevRules[index].value[range] = inputVal;
      } else {
        prevRules[index].value = inputVal;
      }
      return [...prevRules];
    });
  };

  const onClear = () => {
    if (value && value.length > 0) {
      onChange && onChange([]);
    }
  };

  const onReset = () => {
    setRules([
      {
        type: 'keyword',
        rule: '',
        value: '',
        placeholder: '请输入地址关键字',
        width: 180,
      },
    ]);
  };

  const onAddRules = rule => {
    const { length: andNum } = rules.filter(val => val.rule == 'and');
    const { length: oddNum } = rules.filter(val => val.rule == 'odd');
    const { length: evenNum } = rules.filter(val => val.rule == 'even');
    const { length: rangeNum } = rules.filter(val => val.rule == 'range');

    let ruleConfig = {};
    const lastRules = rules[rules.length - 1] || {};
    const hasEmptyAnd = lastRules.rule == 'and' && !lastRules.value;
    switch (rule) {
      case 'and':
        ruleConfig = {
          type: 'and',
          rule,
          value: '',
          width: 100,
          showAnd: true,
          placeholder: `关键字${andNum + 1}`,
        };
        if (andNum >= 5) {
          message.error('‘并且’最多出现5次');
          return;
        }
        setRules(prevRules => [...prevRules, ruleConfig]);
        break;
      case 'odd':
        ruleConfig = {
          type: 'odd',
          rule,
          value: '奇数',
          placeholder: '门牌号奇数',
          showAnd: hasEmptyAnd,
        };
        if (oddNum > 0 || evenNum > 0) {
          message.error('门牌号、门牌号奇数或者门牌号偶数只可添加一次');
          return;
        }
        setRules(prevRules => {
          if (hasEmptyAnd) {
            prevRules.splice(rules.length - 1, 1);
          }
          return [...prevRules, ruleConfig];
        });
        break;
      case 'even':
        ruleConfig = {
          type: 'even',
          rule,
          value: '偶数',
          placeholder: '门牌号偶数',
          showAnd: hasEmptyAnd,
        };
        if (oddNum > 0 || evenNum > 0) {
          message.error('门牌号、门牌号奇数或者门牌号偶数只可添加一次');
          return;
        }
        setRules(prevRules => {
          if (hasEmptyAnd) {
            prevRules.splice(rules.length - 1, 1);
          }
          return [...prevRules, ruleConfig];
        });
        break;
      case 'range':
        ruleConfig = {
          type: 'range',
          rule,
          value: [],
          width: 100,
          placeholder: '门牌号',
          showAnd: hasEmptyAnd,
        };
        if (rangeNum > 0) {
          message.error('门牌号、门牌号奇数或者门牌号偶数只可添加一次');
          return;
        }
        setRules(prevRules => {
          if (hasEmptyAnd) {
            prevRules.splice(rules.length - 1, 1);
          }
          return [...prevRules, ruleConfig];
        });
        break;
      default:
        break;
    }
  };

  useEffect(() => {
    onReset();
  }, []);

  return (
    <Row type="flex" gutter={[0, 10]} className={styles.wrapper}>
      <Col span={24} className={styles.keyWords}>
        <Row type="flex">
          {value.map((keyWord, i) => (
            <Tag key={i} closable onClose={e => onDelete(e, i)}>
              {keyWord}
            </Tag>
          ))}
        </Row>
      </Col>
      <Popconfirm title="确认清空？" onConfirm={onClear}>
        <a className={styles.clear}>清空</a>
      </Popconfirm>
      <Col span={24}>
        <Row type="flex" gutter={[10]} className={styles.blue}>
          {rules.map((item, index) => (
            <Col key={index}>
              <Row type="flex">
                {item.showAnd && <Col>{index > 0 && <span style={{ margin: 5 }}>并且</span>}</Col>}
                <Col>
                  {['odd', 'even'].includes(item.rule) ? (
                    item.placeholder
                  ) : item.type == 'range' ? (
                    <Row type="flex" align="middle" gutter={[10, 0]}>
                      <Col>
                        <Input
                          value={item.value[0]}
                          style={{ width: item.width }}
                          allowClear
                          onChange={e => onInputChange(e, item.rule, index, '0')}
                          placeholder="门牌号"
                        />
                      </Col>
                      <Col>至</Col>
                      <Col>
                        <Input
                          value={item.value[1]}
                          style={{ width: item.width }}
                          allowClear
                          onChange={e => onInputChange(e, item.rule, index, '1')}
                          placeholder="门牌号"
                        />
                      </Col>
                    </Row>
                  ) : (
                    <Input
                      style={{ width: item.width }}
                      allowClear
                      value={item.value}
                      onChange={e => onInputChange(e, item.rule, index)}
                      placeholder={item.placeholder}
                    />
                  )}
                </Col>
              </Row>
            </Col>
          ))}
          <Col>
            <Button onClick={onAdd} size="small" type="primary">
              添加
            </Button>
          </Col>
          <Col>
            <Button onClick={onReset} size="small" type="primary">
              重置
            </Button>
          </Col>
        </Row>
      </Col>
      <Col span={24}>
        <Row type="flex" gutter={[20, 0]}>
          <Col>
            <a onClick={onAddRules.bind(null, 'and')}>并且</a>
          </Col>
          <Col>
            <a onClick={onAddRules.bind(null, 'odd')}>门牌号奇数</a>
          </Col>
          <Col>
            <a onClick={onAddRules.bind(null, 'even')}>门牌号偶数</a>
          </Col>
          <Col>
            <a onClick={onAddRules.bind(null, 'range')}>门牌号多少至多少</a>
          </Col>
          <Col>
            <Popover content={infoContent}>
              <Icon style={{ cursor: 'pointer' }} type="question-circle" />
            </Popover>
          </Col>
        </Row>
      </Col>
    </Row>
  );
});

export default KeyWordsInput;
